//@ts-nocheck
import React, { useEffect, useImperativeHandle } from 'react'

import * as echarts from 'echarts/lib/echarts'
import 'echarts/lib/component/tooltip'
import 'echarts/lib/component/grid'
import 'echarts/lib/chart/bar'
import { Option, ChartsInstance } from '../Bar/interface'

import './index.less'

let echartsInstance: any
let data: Array<Option> = []

interface IProps {
  chartId?: string
  options?: Array<Option>
  chartRef?: React.MutableRefObject<ChartsInstance>
  seriesName?: string
}

const Strip: React.FC<IProps> = ({ options, chartId, chartRef, seriesName = '' }) => {
  useEffect(() => {
    echartsInstance = echarts.init(document.getElementById(chartId || 'strip-bar-chart'))
    setOptions()
  }, [])

  useEffect(() => {
    data = options
    if (echartsInstance) setOptions()
  }, [options])

  useImperativeHandle(chartRef, () => ({
    getInstance: () => {
      return echartsInstance
    }
  }))

  const setOptions = () => {
    let _xAxis = []
    let seriesData = []
    data.forEach((item, itemIndex) => {
      _xAxis.push(item.choiceContent)
      const _barColor = 'rgba(63,96,252, ' + (1 - itemIndex * 0.06) + ')'
      if (item.isSelect) {
        seriesData.push({
          name: item.choiceContent,
          value: item.choiceCount,
          itemStyle: {
            color: _barColor,
            borderWidth: 4,
            borderColor: '#fff',
            shadowColor: 'rgba(0, 10, 59, 0.4)',
            shadowBlur: 10,
            shadowOffsetY: 2
          }
        })
      } else {
        seriesData.push({
          name: item.choiceContent,
          value: item.choiceCount,
          itemStyle: {
            color: _barColor
          }
        })
      }
    })
    echartsInstance.setOption({
      tooltip: {},
      grid: {
        left: '6%',
        top: 10,
        bottom: 50,
        right: '6%'
      },
      xAxis: {
        type: 'value',
        minInterval: 1
      },
      yAxis: {
        type: 'category',
        data: _xAxis,
        axisLabel: {
          show: true,
          interval: 0,
          formatter: (name, dataIndex) => {
            let xName: string = name
            if (xName.length > 4) {
              xName = xName.substring(0, 3) + '...'
            }
            return `{a|${xName}}`
          },
          rich: {
            a: {
              color: '#8B98A9',
              lineHeight: 20,
              fontSize: 10,
              marginBottom: 10
            }
          }
        }
      },
      series: [
        {
          name: seriesName,
          type: 'bar',
          data: [...seriesData],
          itemStyle: {
            borderRadius: [0, 4, 4, 0]
          },
          barMaxWidth: 23
        }
      ]
    })
  }

  return <div className="strip-bar-chart" id={chartId || 'strip-bar-chart'} />
}
export default (Strip)
